package net.example.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.oraycn.esbasic.helpers.StringHelper;

import net.example.model.ChatInfo;
import net.example.utils.SDKUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ChatMessageRecordPersister {
    private ChatMessageRecordPersister(){}

    private static ChatMessageRecordPersister instance =new ChatMessageRecordPersister();
    public static ChatMessageRecordPersister getInstance() {
        return instance;
    }

    public List<ChatInfo> getPage(String speakerID, String audienceID,int pagesize,int rowIndex)
    {
        SQLiteDatabase db = DatabaseHelper.getInstance().getReadableDatabase();
        ArrayList<ChatInfo> list = new ArrayList();
        String sql = "select AutoID, Content from ChatMessageRecord where " +
                "((SpeakerID=? and AudienceID=?) or (SpeakerID=? and AudienceID=?)) " +
                "order by OccureTime desc limit ?,?";
        Cursor cursor = db.rawQuery(sql, new String[]{speakerID,audienceID,audienceID,speakerID ,String.valueOf(rowIndex), String.valueOf(pagesize)});
        while (cursor.moveToNext()) {
            ChatInfo chatInfo = (ChatInfo) SDKUtil.deSerialize(cursor.getBlob(1));

            if (chatInfo != null) {
                chatInfo.setAutoID(cursor.getInt(0));
                list.add(chatInfo);
            }
        }
        cursor.close();//关闭结果集
        db.close();//关闭数据库对象
        Collections.reverse(list);

        return list;
    }

    public void update(ChatInfo chatInfo)
    {
        SQLiteDatabase db = DatabaseHelper.getInstance().getWritableDatabase();
        ContentValues values = this.getContentValues(chatInfo);
        String whereClause="AutoID="+chatInfo.getAutoID();
//        String[] whereArgs = new String[]{chatInfo.getSpeakerID(), chatInfo.getAudienceID(), chatInfo.getAudienceID(), chatInfo.getSpeakerID()};
//        db.update(DatabaseHelper.ChatMessageRecord, values, "((SpeakerID=? and AudienceID=?) or (SpeakerID=? and AudienceID=?)) ", whereArgs);
        db.update(DatabaseHelper.ChatMessageRecord, values,whereClause,null);
        db.close();
    }

    public long insert(ChatInfo chatInfo) {
        SQLiteDatabase db = DatabaseHelper.getInstance().getWritableDatabase();
        ContentValues values= this.getContentValues(chatInfo);
        long autoID= db.insert(DatabaseHelper.ChatMessageRecord, "Content", values);
        db.close();
        return autoID;
    }

    /**
     * 获取并设置要插入DB中的数据
     * */
    private ContentValues getContentValues(ChatInfo chatInfo)
    {
        ContentValues values = new ContentValues();
        values.put("SpeakerID", chatInfo.getSpeakerID());
        values.put("AudienceID", chatInfo.getAudienceID());
        values.put("IsGroupChat", chatInfo.isGroupChat());
        values.put("IsRead", chatInfo.isRead());
        values.put("Content", SDKUtil.serialize(chatInfo));
        values.put("OccureTime", chatInfo.getTime().getTime());
        String tag="";
        if(!StringHelper.isNullOrEmpty(chatInfo.snapchatMessageID))
        {
            tag=chatInfo.snapchatMessageID;
        }
        values.put("Tag",tag);
        return values;
    }

    public int delete(String friendID,boolean isGroupChat)
    {
        SQLiteDatabase db = DatabaseHelper.getInstance().getWritableDatabase();
        String whereClause="";
        String[] whereArgs;
        if(isGroupChat)
        {
            whereClause ="(SpeakerID=? or AudienceID=?) and IsGroupChat=1";
            whereArgs =new String[]{friendID,friendID};
        }
        else {
            whereClause ="(SpeakerID=? or AudienceID=?) and IsGroupChat=0";
            whereArgs =new String[]{friendID,friendID};
        }
        int delCount= db.delete(DatabaseHelper.ChatMessageRecord,whereClause,whereArgs);
        db.close();
        return delCount;
    }

    public void delete (long autoID)
    {
        SQLiteDatabase db = DatabaseHelper.getInstance().getWritableDatabase();
        String whereClause="AutoID="+autoID;
        int delCount= db.delete(DatabaseHelper.ChatMessageRecord,whereClause,null);
        db.close();
    }

    private List<ChatInfo> getone(String speakerID, String audienceID)
    {
        SQLiteDatabase db = DatabaseHelper.getInstance().getReadableDatabase();
        ArrayList<ChatInfo> list = new ArrayList();
        String sql = "select AutoID, Content from ChatMessageRecord where " +
                "((SpeakerID=?) or (AudienceID=?)) " ;
        Cursor cursor = db.rawQuery(sql, new String[]{speakerID,audienceID });
        while (cursor.moveToNext()) {
            ChatInfo chatInfo = (ChatInfo) SDKUtil.deSerialize(cursor.getBlob(1));

            if (chatInfo != null) {
                chatInfo.setAutoID(cursor.getInt(0));
                list.add(chatInfo);
            }
        }
        cursor.close();//关闭结果集
        db.close();//关闭数据库对象
        Collections.reverse(list);
        return list;
    }

    /**
     * 根据阅后即焚消息ID删除DB中对应的记录
     * */
    public void delete4SnapchatMessageID(String snapchatMessageID)
    {
        if(StringHelper.isNullOrEmpty(snapchatMessageID))
        {
            return;
        }
        SQLiteDatabase db = DatabaseHelper.getInstance().getWritableDatabase();
        String whereClause="Tag=?" ;
        int delCount= db.delete(DatabaseHelper.ChatMessageRecord,whereClause,new String[]{snapchatMessageID});
        db.close();
    }
}
